/**
 * Copyright 2009 Sergio Bossa
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.googlecode.actorom.remote;

import com.googlecode.actorom.Actor;
import com.googlecode.actorom.Address;
import com.googlecode.actorom.FailoverPolicy;
import com.googlecode.actorom.FutureResult;
import com.googlecode.actorom.ThreadingPolicy;
import com.googlecode.actorom.Topology;
import com.googlecode.actorom.impl.core.AbstractTopology;
import com.googlecode.actorom.impl.remote.channel.protocol.PingCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.SpawnCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.SwapCommand;
import com.googlecode.actorom.support.ThreadingPolicies;
import com.googlecode.actorom.impl.remote.channel.RemoteChannel;
import com.googlecode.actorom.impl.remote.channel.ServerCallback;
import com.googlecode.actorom.impl.remote.channel.protocol.Ack;
import com.googlecode.actorom.impl.remote.channel.ResponseCallback;
import com.googlecode.actorom.impl.remote.channel.protocol.CompleteFutureCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.IsActiveCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.LinkCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.SendCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.SendWithFutureCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.UnlinkCommand;
import com.googlecode.actorom.support.FailoverPolicies;
import com.googlecode.actorom.support.TopologyException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import net.jcip.annotations.ThreadSafe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Remote {@link com.googlecode.actorom.Topology} implementation following the client/server paradigm.<br>
 * Every server topology, bound to a specific host address and port by using TCP sockets, enables remote {@link ClientTopology} instances
 * to connect and use its services and actors.
 * <br><br>
 * Please note that if used locally, the server topology will normally spawn and access its own, local, actors.
 *
 * @author Sergio Bossa
 */
@ThreadSafe
public class ServerTopology extends AbstractTopology {

    private static final transient Logger LOG = LoggerFactory.getLogger(ServerTopology.class);
    private final String host;
    private final int port;
    private final RemoteChannel serverChannel;

    /**
     * Create a server topology using the following defaults:
     * <ul>
     * <li>{@link com.googlecode.actorom.support.ThreadingPolicies#newOSThreadingPolicy(int )}, using a thread pool
     * with a number of fixed threads equal to the available processors.</li>
     * <li>{@link com.googlecode.actorom.support.FailoverPolicies#newNoFailoverPolicy()}.</li>
     * </ul>
     *
     * @param host The host address this topology will listen to for remote connections.
     * @param port The port this topology will listen to for remote connections.
     */
    public ServerTopology(String host, int port) {
        this(host, port, ThreadingPolicies.newGreenThreadingPolicy(), FailoverPolicies.newNoFailoverPolicy());
    }

    /**
     * Create a server topology using the provided {@link com.googlecode.actorom.ThreadingPolicy},
     * and the {@link com.googlecode.actorom.support.FailoverPolicies#newNoFailoverPolicy()} default.
     *
     * @param host The host address this topology will listen to for remote connections.
     * @param port The port this topology will listen to for remote connections.
     * @param threadingPolicy
     */
    public ServerTopology(String host, int port, ThreadingPolicy threadingPolicy) {
        this(host, port, threadingPolicy, FailoverPolicies.newOneForOnePolicy());
    }

    /**
     * Create a server topology using the provided {@link com.googlecode.actorom.FailoverPolicy},
     * and the {@link com.googlecode.actorom.support.ThreadingPolicies#newGreenThreadingPolicy()} default.
     *
     * @param host The host address this topology will listen to for remote connections.
     * @param port The port this topology will listen to for remote connections.
     * @param failoverPolicy
     */
    public ServerTopology(String host, int port, FailoverPolicy failoverPolicy) {
        this(host, port, ThreadingPolicies.newGreenThreadingPolicy(), failoverPolicy);
    }

    /**
     * Create a remote server using the provided {@link com.googlecode.actorom.ThreadingPolicy} and
     * {@link com.googlecode.actorom.FailoverPolicy}.
     *
     * @param host The host address this topology will listen to for remote connections.
     * @param port The port this topology will listen to for remote connections.
     * @param threadingPolicy
     * @param failoverPolicy
     */
    public ServerTopology(String host, int port, ThreadingPolicy threadingPolicy, FailoverPolicy failoverPolicy) {
        super(threadingPolicy, failoverPolicy);
        try {
            this.host = host;
            this.port = port;
            this.serverChannel = new RemoteChannel(host, port, new ServerCallbackImpl());
            this.serverChannel.bind();
        } catch (IOException ex) {
            throw new TopologyException(ex.getMessage(), ex);
        }
    }

    public final synchronized Address spawnActor(String id, Object handler) {
        Address address = Address.newRemoteAddress(host, port, id);
        boolean spawned = doSpawnActor(address, handler);
        if (spawned) {
            return address;
        } else {
            return null;
        }
    }

    public final synchronized Actor spawnAndGetActor(String id, Object handler) {
        Address address = Address.newRemoteAddress(host, port, id);
        boolean spawned = doSpawnActor(address, handler);
        if (spawned) {
            return doGetActor(address);
        } else {
            return null;
        }
    }

    public final synchronized Actor getActor(Address address) {
        if (address.isRemote() && address.getHost().equals(host) && address.getPort() == port) {
            return doGetActor(address);
        } else {
            throw new TopologyException("Not a remote address for this server topology: " + address);
        }
    }

    public final synchronized void shutdown() {
        serverChannel.unbind();
        doShutdown();
    }

    private class ServerCallbackImpl implements ServerCallback {

        public void spawnActor(SpawnCommand command, ResponseCallback callback) {
            Address address = Address.newRemoteAddress(host, port, command.getId());
            boolean spawned = doSpawnActor(address, command.getHandler());
            if (spawned) {
                LOG.debug("Remotely spawned actor at address {}", address);
                callback.write(new Ack(command.getHeader(), true));
            } else {
                callback.write(new Ack(command.getHeader(), false));
            }
        }

        public void swapHandler(SwapCommand command, ResponseCallback callback) {
            Actor actor = doGetActor(command.getAddress());
            if (actor != null) {
                LOG.debug("Remotely swapping handler of actor at address {}", actor.getAddress());
                actor.swap(command.getHandler());
                callback.write(new Ack(command.getHeader(), true));
            } else {
                LOG.warn("No actor at address {}", actor.getAddress());
                callback.write(new Ack(command.getHeader(), false));
            }
        }

        public void sendMessage(SendCommand command, ResponseCallback callback) {
            Actor recipientActor = doGetActor(command.getRecipient());
            if (recipientActor != null) {
                LOG.debug("Remotely sending message to actor at address {}", recipientActor.getAddress());
                recipientActor.send(command.getMessage());
                callback.write(new Ack(command.getHeader(), true));
            } else {
                LOG.warn("No actor at address {}", recipientActor.getAddress());
                callback.write(new Ack(command.getHeader(), false));
            }
        }

        public void sendMessageWithFuture(final SendWithFutureCommand command, ResponseCallback callback) {
            Actor recipientActor = doGetActor(command.getRecipient());
            if (recipientActor != null) {
                LOG.debug("Remotely sending message to actor at address {}", recipientActor.getAddress());
                FutureResult future = recipientActor.send(command.getMessage(), command.getTimeoutInNanos(), TimeUnit.NANOSECONDS);
                callback.write(new Ack(command.getHeader(), true));
                future.await();
                if (future.isCompleted()) {
                    callback.write(new CompleteFutureCommand(command.getHeader(), recipientActor.getAddress(), future.getResult(), future.getException()));
                } else {
                    // FIXME : it should be ok not to do anything here.
                }
            } else {
                LOG.warn("No actor at address {}", recipientActor.getAddress());
                callback.write(new Ack(command.getHeader(), false));
            }
        }

        public void linkActor(LinkCommand command, ResponseCallback callback) {
            Address fromAddress = command.getFromAddress();
            Actor fromActor = doGetActor(fromAddress);
            if (fromActor != null) {
                Address toAddress = command.getToAddress();
                Actor toActor = doGetActor(toAddress);
                if (toActor != null) {
                    LOG.debug("Remotely linking actor at address {} to actor at address {}", fromAddress, toAddress);
                    fromActor.link(toActor);
                    callback.write(new Ack(command.getHeader(), true));
                } else {
                    LOG.warn("No actor at address {}", toAddress);
                    callback.write(new Ack(command.getHeader(), false));
                }
            } else {
                LOG.warn("No actor at address {}", fromAddress);
                callback.write(new Ack(command.getHeader(), false));
            }
        }

        public void unlinkActor(UnlinkCommand command, ResponseCallback callback) {
            Address sourceAddress = command.getSourceAddress();
            Actor sourceActor = doGetActor(sourceAddress);
            if (sourceActor != null) {
                Address fromAddress = command.getFromAddress();
                Actor fromActor = doGetActor(fromAddress);
                if (fromActor != null) {
                    LOG.debug("Remotely unlinking actor at address {} from actor at address {}", sourceAddress, fromAddress);
                    sourceActor.unlink(fromActor);
                    callback.write(new Ack(command.getHeader(), true));
                } else {
                    LOG.warn("No actor at address {}", fromAddress);
                    callback.write(new Ack(command.getHeader(), false));
                }
            } else {
                LOG.warn("No actor at address {}", sourceAddress);
                callback.write(new Ack(command.getHeader(), false));
            }
        }

        public void isActiveActor(IsActiveCommand command, ResponseCallback callback) {
            Actor actor = doGetActor(command.getAddress());
            if (actor != null && actor.isActive()) {
                callback.write(new Ack(command.getHeader(), true));
            } else {
                callback.write(new Ack(command.getHeader(), false));
            }
        }

        public void sendPingResponse(PingCommand command, ResponseCallback callback) {
            callback.write(new Ack(command.getHeader(), true));
        }
    }
}
